package com.example.im.service.impl;

import com.example.im.model.Group;
import com.example.im.model.Message;
import com.example.im.service.GroupService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class GroupServiceImpl implements GroupService {
    private static final Logger log = LoggerFactory.getLogger(GroupServiceImpl.class);
    @Resource
    private JdbcTemplate jdbcTemplate;
    private Logger logger = LoggerFactory.getLogger(GroupServiceImpl.class);
    //持久化创建的新群聊
    @Override
    public void createGroup(Group group) {
        String sql = "INSERT INTO group_info (group_id, group_user, group_owner,group_member) VALUES (?, ?,?,?)";
        jdbcTemplate.update(sql,
                group.getGroup_id(),
                null,
                group.getGroup_owner(),
                1
        );
    }

    //获取群聊成员字符串
    public String getUsersExisted(String groupId){
        logger.info(groupId);
        String sql = "SELECT group_user FROM group_info WHERE group_id = ?";
        return jdbcTemplate.queryForObject(sql,String.class, groupId);
    }

    public List<String> convertToList(String usersExisted){
        List<String> resultList = Arrays.stream(usersExisted.split("\\$"))
                .collect(Collectors.toList());
        return resultList;
    }


    //获取群聊成员数量
    private int getGroupMember(String groupId){
        String sql = "SELECT group_member FROM group_info WHERE group_id = ?";
        return jdbcTemplate.queryForObject(sql,Integer.class, groupId);
    }

    private boolean ifExisted(String usersInGroup, String user){
        List<String> users=convertToList(usersInGroup);
        for(String pickUser:users){
            if(pickUser.equals(user)){
                return false;
            }
        }
        return true;
    }
    //将加入的成员持久化
    @Override
    public void joinGroup(String groupId, String user) {
        if(getUsersExisted(groupId)!=null&&!ifExisted(getUsersExisted(groupId),user)){
            return;
        }
        String usersInGroup="";
        int groupMember = getGroupMember(groupId);
        if(getUsersExisted(groupId)!=null&&!getUsersExisted(groupId).equals("null")&&ifExisted(usersInGroup,user)){
            usersInGroup =getUsersExisted(groupId)+"$"+user;
            groupMember++;
        }
        else {
            usersInGroup =user;

        }
        log.info("现在的组员:"+getUsersExisted(groupId));
        String sql = "UPDATE group_info SET group_user = ? , group_member= ? WHERE group_id = ?";
        jdbcTemplate.update(sql,
                usersInGroup,
                groupMember,
                groupId
        );
    }
    @Override
    public int countsInMember(String user){
        String sql="SELECT * from group_info";
        List<Group> groupList=jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Group.class));
        int count=1;
        for(Group group:groupList){
            String usersInGroup=group.getGroup_user();
            String[] parts = usersInGroup.split("\\$");
            for(String part:parts){
                if(part.equals(user)){
                    count++;
                }
            }
        }
        return count;
    }

    @Override
    public Set<String> getGroupsByUser(String user) {
        String sql="SELECT * from group_info";
        List<Group> groupList=jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Group.class));
        Set<String> exist= new LinkedHashSet<>();
        exist.add("G00001");
        logger.info(user);
        Set<String> notExist= new LinkedHashSet<>();
        for(Group group:groupList){
            String usersInGroup=group.getGroup_user();
            String[] parts = usersInGroup.split("\\$");
            boolean flag=false;
            for(String part:parts){
                if(part.equals(user)){
                    exist.add(group.getGroup_id());
                    flag=true;
                    break;
                }
            }
            if(!flag){
                notExist.add(group.getGroup_id());
            }
        }
        logger.info(String.valueOf(exist));
        exist.addAll(notExist);
        return exist;
    }
    @Override
    public List<Group> getAllGroups(){
        String sql="SELECT * from group_info";
        List<Group> groupList=jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Group.class));
        return groupList;
    }
}
